package com.stark.wechat.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.stark.wechat.interceptor.MonitorInterceptor;
import com.stark.wechat.interceptor.ScopeInterceptor;

/**
 * Spring MVC 配置。
 * @author mengbin
 * @since 1.1.0
 * @version 1.0.0, 2017/9/22
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.stark.wechat",
	useDefaultFilters = false,
	includeFilters = @Filter({ Controller.class, ControllerAdvice.class }))
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		registry.jsp("/WEB-INF/jsp/", ".jsp");
		registry.enableContentNegotiation(new MappingJackson2JsonView());
		super.configureViewResolvers(registry);
	}
	
	@Override
	public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
		// 内容协商，默认根据 URL 后缀名匹配，设置为 false 表示根据 Access 头确定返回类型
		configurer.favorPathExtension(false);
		super.configureContentNegotiation(configurer);
	}
	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
		super.addResourceHandlers(registry);
	}
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new ScopeInterceptor());
		registry.addInterceptor(new MonitorInterceptor(5000L));
		super.addInterceptors(registry);
	}
	
	@Bean
	@Description("文件上传表单视图解析器")
	public CommonsMultipartResolver multipartResolver() {
		return new CommonsMultipartResolver();
	}
}
